<template>
    <NuxtLayout name="manage-layout">
        <template #main>
            <div class="min-h-dvh flex justify-center">
                <div class="card bg-base-100 w-11/12 shadow-xl">
                    <div class="card-body">
                        <h4 class="card-title">学校管理</h4>
                        <div class="stats shadow w-56">
                            <div class="stat">
                                <div class="stat-figure text-secondary cursor-pointer" @click="showFormModal(null)" v-if="'超级管理员' === loginUserRef.role">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                         stroke-width="1.5"
                                         stroke="currentColor" class="size-6">
                                        <path stroke-linecap="round" stroke-linejoin="round"
                                              d="M12 4.5v15m7.5-7.5h-15"/>
                                    </svg>
                                </div>
                                <div class="stat-title">数据量</div>
                                <div class="stat-value">{{ tableData.total }}</div>
                                <div class="stat-desc">共{{tableData.pages}}页数据</div>
                            </div>
                        </div>

                        <div class="flex flex-col gap-2">
                            <div class="flex flex-wrap gap-6">
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">学校名称</span>
                                    </label>
                                    <input type="text" v-model="searchForm.name"
                                           placeholder="请输入学校名称"
                                           class="input input-md input-bordered"/>
                                </div>
                            </div>
                        </div>
                        <div class="flex">
                            <button class="btn btn-square btn-outline btn-md btn-info" @click="loadData()"
                                    title="查询">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                     stroke-width="1.5"
                                     stroke="currentColor" class="size-6">
                                    <path stroke-linecap="round" stroke-linejoin="round"
                                          d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"/>
                                </svg>
                            </button>
                        </div>

                        <div class="card bg-base-100 w-full shadow-xl">
                            <div class="card-body">
                                <div class="overflow-x-auto">
                                    <table class="table">
                                        <thead>
                                        <tr>
                                            <th>学校名称</th>
                                            <th>地址</th>
                                            <th></th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <tr v-for="item in tableData.list" class="hover">
                                            <td>{{item.name}}</td>
                                            <td>{{item.address}}</td>
                                            <td>
                                                <button class="btn btn-xs mx-1 hover:bg-cyan-400" @click="showFormModal(item.id)"
                                                        :disabled="'超级管理员' !== loginUserRef.role"
                                                        title="编辑">
                                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none"
                                                         viewBox="0 0 24 24" stroke-width="1.5"
                                                         stroke="currentColor" class="size-6 hover:text-white">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                              d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"/>
                                                    </svg>
                                                </button>
                                                <button class="btn btn-xs mx-1 hover:bg-rose-400" @click="del(item.id)"
                                                        :disabled="'超级管理员' !== loginUserRef.role"
                                                        title="删除">
                                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none"
                                                         viewBox="0 0 24 24" stroke-width="1.5"
                                                         stroke="currentColor" class="size-6 hover:text-white">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                              d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"/>
                                                    </svg>
                                                </button>
                                            </td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="card-actions justify-center mt-6">
                            <button @click="toPage(item)"
                                    :class="'join-item btn-xs btn' + (item === searchForm.page ? ' btn-neutral ' : '')"
                                    v-for="item in tableData.pagination">{{ item }}
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 编辑弹出层 -->
                <dialog-modal ref="formDialogModalRef">
                    <template #main>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">学校名称</span>
                            </label>
                            <input type="text" v-model="form.name" placeholder="请输入学校名称"
                                   class="input input-md input-bordered"
                                   :class="{'input-error': formErrors.name}"
                                   @input="validateName"/>
                            <label class="label" v-if="formErrors.name">
                                <span class="label-text-alt text-error">{{formErrors.name}}</span>
                            </label>
                        </div>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">地址</span>
                            </label>
                            <input type="text" v-model="form.address" placeholder="请输入学校地址"
                                   class="input input-md input-bordered"
                                   :class="{'input-error': formErrors.address}"
                                   @input="validateAddress"/>
                            <label class="label" v-if="formErrors.address">
                                <span class="label-text-alt text-error">{{formErrors.address}}</span>
                            </label>
                        </div>
                    </template>
                    <template #footer>
                        <div>
                            <button class="btn bg-green-400 hover:bg-green-500 text-white" @click="submitForm()">提交</button>
                        </div>
                    </template>
                </dialog-modal>
            </div>
        </template>
    </NuxtLayout>
</template>

<script setup>
import {httpDel, httpGet, httpPost} from "~/utils/http/http-helper.js";
import {generatePaginationArray} from "~/utils/pagination/index.js";
import {notificationError, notificationSuccess} from "~/utils/notification/index.js";
import auth from "~/utils/auth/index.js";

definePageMeta({
    index: 'manage-school',
})

const formDialogModalRef = ref()

const searchForm = ref({
    page: 1,
    size: 10,
    name: undefined
})

const tableData = ref({
    list: [],
    total: 0,
    pages: '',
    pagination: []
})

const form = ref({})
const formErrors = ref({})
const loginUserRef = ref({})
const detailsData = ref(null)

/**
 * 加载登录用户
 */
function loadLoginUser(){
    const localUser = auth.getLocalUser()
    if(null !== localUser){
        loginUserRef.value = localUser
    }
}

/**
 * 初始化表单
 */
function initForm() {
    form.value = {}
    formErrors.value = {}
}

/**
 * 表单验证
 */
function validateName() {
    if (!form.value.name) {
        formErrors.value.name = '请输入学校名称'
    } else if (form.value.name.length > 50) {
        formErrors.value.name = '学校名称不能超过50个字符'
    } else {
        formErrors.value.name = ''
    }
}

/**
 * 地址验证
 */
function validateAddress() {
    if (!form.value.address) {
        formErrors.value.address = '请输入学校地址'
    } else if (form.value.address.length > 200) {
        formErrors.value.address = '地址不能超过200个字符'
    } else {
        formErrors.value.address = ''
    }
}

/**
 * 加载数据
 */
async function loadData() {
    try {
        const response = await httpGet('/api/school', {
            pageNum: searchForm.value.page,
            pageSize: searchForm.value.size,
            name: searchForm.value.name
        })
        
        if (response.code === '0') {
            const data = response.data
            tableData.value = {
                list: data.content,
                total: data.totalElements,
                pages: data.pages,
                pagination: generatePaginationArray(data.pages, searchForm.value.page)
            }
        } else {
            notificationError(response.msg || '加载数据失败')
        }
    } catch (error) {
        notificationError('加载数据失败')
        console.error('Error loading data:', error)
    }
}

/**
 * 跳转到指定页
 */
function toPage(page) {
    searchForm.value.page = page
    loadData()
}

/**
 * 显示表单弹窗
 */
function showFormModal(id) {
    initForm()
    if (id) {
        detailsData.value = id
        loadDetails(id)
    } else {
        detailsData.value = null
        formDialogModalRef.value.showDialogModal('添加学校')
    }
}

/**
 * 加载详情
 */
async function loadDetails(id) {
    try {
        const response = await httpGet(`/api/school/${id}`)
        if (response.code === '0') {
            form.value = response.data
            formDialogModalRef.value.showDialogModal('修改学校')
        } else {
            notificationError(response.msg || '加载详情失败')
        }
    } catch (error) {
        notificationError('加载详情失败')
        console.error('Error loading details:', error)
    }
}

/**
 * 关闭表单弹窗
 */
function closeFormModal() {
    formDialogModalRef.value.closeDialogModal()
    initForm()
    detailsData.value = null
}

/**
 * 表单提交
 */
async function submitForm() {
    validateName()
    validateAddress()
    
    if (Object.values(formErrors.value).some(error => error)) {
        notificationError('请修正表单中的错误')
        return
    }

    try {
        let response
        if (detailsData.value === null) {
            // Add new school
            response = await httpPost('/api/school', form.value)
        } else {
            // Update existing school
            response = await httpPost(`/api/school/${detailsData.value}`, form.value)
        }

        if (response.code === '0') {
            notificationSuccess(detailsData.value === null ? '添加学校成功' : '编辑学校成功')
            closeFormModal()
            loadData()
        } else {
            notificationError(response.msg || '操作失败')
        }
    } catch (error) {
        notificationError('操作失败')
        console.error('Error submitting form:', error)
    }
}

/**
 * 删除学校
 */
async function del(id) {
    if (!confirm('确定要删除该学校吗？')) {
        return
    }

    try {
        const response = await httpDel(`/api/school/${id}`)
        if (response.code === '0') {
            notificationSuccess('删除成功')
            loadData()
        } else {
            notificationError(response.msg || '删除失败')
        }
    } catch (error) {
        notificationError('删除失败')
        console.error('Error deleting school:', error)
    }
}

if (process.client) {
    loadLoginUser()
    loadData()
}

</script>

<style scoped>
</style> 